import os
import sys
import time
import logging
from typing import List
import winerror
import traceback
import win32event
import win32service
import win32timezone
import servicemanager
import win32serviceutil
from win32service import OpenSCManager
from win32service import OpenService
from win32service import QueryServiceStatus
from workers02.WS0210 import WorkWS0210
from workers02.WS0211 import WorkWS0211
from workers02.WS0212 import WorkWS0212
from workers02.WS0214 import WorkWS0214
from workers02.WS0215 import WorkWS0215
from workers02.WS0216 import WorkWS0216
from workers02.WS0217 import WorkWS0217
from workers02.WS0218 import WorkWS0218




logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s: %(message)s")
services: List[dict] = [
    {
        "routine": None,
        "model": "WorkWS0210()"
    },
    {
        "routine": None,
        "model": "WorkWS0211()"
    },
    {
        "routine": None,
        "model": "WorkWS0212()"
    },
    {
        "routine": None,
        "model": "WorkWS0214()"
    },
    {
        "routine": None,
        "model": "WorkWS0215()"
    },
    {
        "routine": None,
        "model": "WorkWS0216()"
    },
    {
        "routine": None,
        "model": "WorkWS0217()"
    },
    {
        "routine": None,
        "model": "WorkWS0218()"
    },


]


class AppKZLServicesViSu01B(win32serviceutil.ServiceFramework):
    # 注册服务名
    _svc_name_ = "AppKZLServicesViSu01B"
    # 服务在windows系统中显示的名称
    _svc_display_name_ = "AppKZLServicesViSu01B"
    # 服务描述
    _svc_description_ = "AppKZLServicesViSu01B"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.status: bool = True

    def SvcDoRun(self):
        time.sleep(2.8)
        # noinspection PyBroadException
        try:
            while True:
                for f_index, f_itr in enumerate(services):
                    if f_itr.get("routine") is None or f_itr.get("routine").is_alive() is False:
                        f_itr["routine"] = eval(f_itr.get("model"))
                        f_itr["routine"].start()
                time.sleep(2.8)
        except Exception as e:
            logging.error(msg=traceback.print_exc())

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        self.status = False


if __name__ == '__main__':
    if len(sys.argv) == 1:
        try:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(AppKZLServicesViSu01B)
            servicemanager.StartServiceCtrlDispatcher()
        except Exception as details:
            if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(AppKZLServicesViSu01B)

    # noinspection PyBroadException
    try:
        while True:
            for f_index0, f_itr0 in enumerate(services):
                if f_itr0.get("routine") is None or f_itr0.get("routine").is_alive() is False:
                    f_itr0["routine"] = eval(f_itr0.get("model"))
                    f_itr0["routine"].start()
            time.sleep(2.8)
    except Exception as e:
        logging.error(msg=traceback.print_exc())
